package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.CheckInPeopleAddDTO;
import org.jsola.hr.dto.CheckInPeopleUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.CheckInPeopleQuery;
import org.jsola.hr.query.StatisicsPageEmpExportQuery;
import org.jsola.hr.service.ICheckInPeopleService;
import org.jsola.hr.vo.CheckInPeopleListVO;
import org.jsola.hr.vo.CheckInPeopleVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;


/**
 * 预登记人员
 *
 * @author zhr
 */
@RestController("hrCheckInPeopleController")
@RequestMapping(HrConstants.API_PATH + "/v1/checkInPeoples")
public class CheckInPeopleController implements ICheckInPeopleControllerAPI {

    @Autowired
    private ICheckInPeopleService checkInPeopleService;

    @Override
    @PostMapping("/identificationCard")
    public Result<CheckInPeopleListVO> identificationCard(@Valid @RequestBody CheckInPeopleQuery checkInPeopleQuery) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                checkInPeopleService.identificationCard(checkInPeopleQuery, tokenUser)
        );
    }

    @Override
    @PutMapping("/batchUpdate")
    public Result<Integer> batchUpdate(@Valid @RequestBody CheckInPeopleUpdateDTO checkInPeopleUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                checkInPeopleService.batchUpdate(checkInPeopleUpdateDTO, tokenUser)
        );
    }

    @Override
    @PostMapping
    public Result<CheckInPeopleVO> save(@Valid @RequestBody CheckInPeopleAddDTO checkInPeopleAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增预登记人员权限校验

        return Result.success(
                checkInPeopleService.save(checkInPeopleAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveForMini")
    public Result<CheckInPeopleVO> saveForMini(@Valid @RequestBody CheckInPeopleAddDTO checkInPeopleAddDTO) {
        TokenUser tokenUser = new TokenUser();
        tokenUser.setSiteId(checkInPeopleAddDTO.getSiteId());
        tokenUser.setUserId(checkInPeopleAddDTO.getUserId());

        return Result.success(
                checkInPeopleService.save(checkInPeopleAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/importCheckInPeople")
    public Result<List<CheckInPeopleVO>> importCheckInPeople(@RequestParam("file") MultipartFile file) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入解析excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                checkInPeopleService.importCheckInPeople(excelFile, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody CheckInPeopleUpdateDTO checkInPeopleUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改预登记人员权限校验

        int count = checkInPeopleService.update(checkInPeopleUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{checkInPeopleId}")
    public Result<Integer> delete(@PathVariable String checkInPeopleId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除预登记人员权限校验

        int count = checkInPeopleService.deleteByIds(tokenUser, checkInPeopleId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] checkInPeopleIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除预登记人员权限校验

        int count = checkInPeopleService.deleteByIds(tokenUser, checkInPeopleIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{checkInPeopleId}")
    public Result<CheckInPeopleVO> findById(@PathVariable String checkInPeopleId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看预登记人员权限校验

        return Result.success(
                checkInPeopleService.selectById(checkInPeopleId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<CheckInPeopleListVO>> listAll(@Valid CheckInPeopleQuery checkInPeopleQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看预登记人员权限校验

        return Result.success(
                checkInPeopleService.select(checkInPeopleQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<CheckInPeopleListVO>> page(@Valid CheckInPeopleQuery checkInPeopleQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        Page<CheckInPeopleListVO> page = checkInPeopleService.selectPage(checkInPeopleQuery, tokenUser.getSiteId());
        if (Objects.nonNull(checkInPeopleQuery.getIsShowOtherInfo()) && checkInPeopleQuery.getIsShowOtherInfo()) {
            // 添加入职相关信息
            page.getEntities().forEach(checkInPeopleListVO ->
                    checkInPeopleService.setHireDateAndCompanyName(checkInPeopleListVO, tokenUser.getSiteId()));
        }
        checkInPeopleService.setChannelName(page.getEntities(), tokenUser.getSiteId());
        return Result.success(
                page
        );
    }

    @Override
    @GetMapping("/checkInPeopleExport")
    public ResponseEntity<Resource> checkInPeopleExport(@Valid CheckInPeopleQuery checkInPeopleQuery) {
        TokenUser tokenUser = UserContext.getUser();

        // todo 新增员工参保信息表权限校验
        String excelFilePath = checkInPeopleService.checkInPeopleExport(checkInPeopleQuery, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PostMapping("/checkTodayAddExport")
    public ResponseEntity<Resource> checkTodayAddExport(@Valid @RequestBody StatisicsPageEmpExportQuery statisicsPageEmpExportQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // 模板文件
        InputStream is = checkInPeopleService.checkTodayAddExport(statisicsPageEmpExportQuery, tokenUser);
        ParamException.notNull(is, "模板生成失败");

        // 编码文件名，防止乱码
        String filenames = new String("今日新增预登记".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel")
                .body(new InputStreamResource(is));
    }

    @Override
    @GetMapping("/pageForMini")
    public Result<Page<CheckInPeopleListVO>> pageForMini(@Valid CheckInPeopleQuery checkInPeopleQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                checkInPeopleService.selectPageForMini(checkInPeopleQuery, tokenUser)
        );
    }
}

